# -*- coding: utf-8 -*-
from settings import db

def getAttrType(attrName):
    result = db.sqlQuery(
        'SELECT attribute_id, backend_type FROM firsteav_attribute where attribute_code like \'%' + attrName + '%\' and entity_type_id=4;')
    if not result:
        result = db.sqlQuery('SELECT attribute_id, backend_type FROM firsteav_attribute where attribute_code =\'' + attrName + '\' and entity_type_id=4;')
        if not result:
            return False, False
    return result[0][0], result[0][1]


def getProductsNameByAttrId(attrId, attrType):
    productsName = []
    productsId = db.sqlQuery(
        'SELECT entity_id FROM firstcatalog_product_entity_' + attrType + ' where attribute_id=' + str(attrId)
        + ' and entity_id in (SELECT entity_id FROM firstcatalog_product_entity_int where attribute_id=(SELECT attribute_id FROM firsteav_attribute where attribute_code=\'status\') and value=1);')
    for productId in productsId:
        result = db.sqlQuery("""SELECT value FROM firstcatalog_product_entity_varchar
        where attribute_id=(SELECT attribute_id FROM firsteav_attribute where attribute_code='name' and entity_type_id=4)
        and entity_id = """ + str(productId[0]))
        productsName.append(result[0][0])
    return productsName


def searchProductsByAttr(attrName):
    attrId, attrType = getAttrType(attrName)
    productsName = None
    if attrId and attrType:
        productsName = getProductsNameByAttrId(attrId, attrType)
    return productsName
